package com.waffle.batterywidget;

import java.util.Arrays;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

class ActiveAppWidgetIdsManager
{
  static int[] activeAppWidgetIds;

  static void clearActiveAppWidgetIds()
  {
    activeAppWidgetIds = null;
  }

  static boolean registerIds(Context context, int[] appWidgetIds)
  {
    boolean newId = false;
    if (context != null)
    {
      SharedPreferences settings = context.getSharedPreferences(BatteryWidget.PREFS_NAME, Context.MODE_PRIVATE);
      if (activeAppWidgetIds == null)
      {
        String savedIds = settings.getString(BatteryWidget.KEY_ACTIVE_IDS, null);
        activeAppWidgetIds = arrayFromString(savedIds);
        newId = true;
      }
      if (activeAppWidgetIds == null)
      {
        int length = appWidgetIds.length;
        activeAppWidgetIds = new int[length];
        System.arraycopy(appWidgetIds, 0, activeAppWidgetIds, 0, length);
        newId = true;
      }
      else
      {
        for (int id : appWidgetIds)
        {
          boolean idAdded = addIdIfNotPresent(id);
          newId |= idAdded;
        }
      }
      if (newId)
      {
        Editor editor = settings.edit();
        editor.putString(BatteryWidget.KEY_ACTIVE_IDS, Arrays.toString(activeAppWidgetIds));
        editor.commit();
      }
    }
    return newId;
  }

  private static boolean addIdIfNotPresent(int id)
  {
    for (int existingId : activeAppWidgetIds)
    {
      if (existingId == id)
      {
        return false;
      }
    }
    int length = activeAppWidgetIds.length;
    int[] newActiveIds = new int[length + 1];
    System.arraycopy(activeAppWidgetIds, 0, newActiveIds, 0, length);
    newActiveIds[length] = id;
    activeAppWidgetIds = newActiveIds;
    return true;
  }

  private static int[] arrayFromString(String input)
  {
    if (input == null)
      return null;
    String[] parts = input.replace("[", "").replace("]", "").split(", ");
    int length = parts.length;
    int[] nums = new int[length];
    for (int i = 0; i < length; i++)
    {
      nums[i] = Integer.parseInt(parts[i]);
    }
    return nums;
  }
}